<template>
  <div>
    <!-- TopCard -->
    <el-card style="height: 80px">
      <el-form class="form">
        <el-form-item label="职位搜索:">
          <el-input v-model="searchKey"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="searchAbout" type="primary">搜索</el-button>
          <el-button type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- TableCard -->
    <el-card class="below_content">
      <el-button type="primary" icon="Plus" @click="addRoleClick">
        添加职位
      </el-button>
      <el-table
        :data="userList"
        @selection-change="handleSelectionChange"
        style="margin: 15px 0"
      >
        <el-table-column label="#" type="index" />
        <el-table-column label="ID" width="80" prop="id" />
        <el-table-column label="职位名称" prop="roleName" />
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="更新时间" prop="updateTime" />
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button @click="setPower(row)" type="success" icon="user">
              分配权限
            </el-button>
            <el-button
              @click="updateRoleName(row)"
              type="primary"
              icon="edit"
            ></el-button>
            <el-button
              @click="removeRole(row)"
              type="danger"
              icon="delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[2, 5, 7, 9]"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @change="handleChange"
      />
    </el-card>
    <!-- 添加/修改职位弹窗 -->
    <el-dialog v-model="dialogAddVisible" title="添加职位" width="500">
      <el-form :model="roleParams">
        <el-form-item class="form_edtxt" label="职位名:">
          <el-input v-model="roleParams.roleName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelAddRole">取消</el-button>
          <el-button type="primary" @click="handleConfirmAddRole">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配角色抽屉 -->
    <el-drawer v-model="setRoleDraw" title="分配用户角色">
      <el-tree
        style="max-width: 600px"
        ref="treeRef"
        :data="roleList"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="selectedArr"
        :props="defaultProps"
      />
      <template #footer>
        <el-button @click="confirmClick" type="primary">确认</el-button>
        <el-button @click="cancelClick" type="primary">取消</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, reactive } from 'vue'
import {
  reqRoleInfo,
  reqAddOrUpdateRole,
  reqDeleteRole,
  reqGetRoleList,
  reqAssignPermission,
} from '../../../api/acl/role'

import { ElMessage } from 'element-plus'
import { ResponseData } from '../../../api/user/type.ts'

let currentPage = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>()
let dialogAddVisible = ref(false) //控制添加role的显示与隐藏
let roleParams = reactive({
  roleName: '',
  id: '',
})
const searchKey = ref<string>('')
const userList = ref([])

const setRoleDraw = ref() // 控制分配权限抽屉的显示与隐藏
const roleList = ref()
const defaultProps = {
  children: 'children',
  label: 'name',
}
const selectedArr = ref()

const treeRef = ref() // 获取树实例

/* func:获取已有职位信息 */
const getHasRoles = async () => {
  let res = await reqRoleInfo(
    currentPage.value,
    pageSize.value,
    searchKey.value,
  )
  if (res.code == 200) {
    total.value = res.data.total
    userList.value = res.data.records
  }
}

/* 分页器change事件 */
let handleChange = () => {
  getHasRoles()
}

/* func:发送添加/修改职位请求 */
const addOrUpdateRole = async () => {
  console.log('addOrUpdateRole')
  let res = await reqAddOrUpdateRole(roleParams)
  console.log(res)
}

/* click: 添加职位按钮 */
const addRoleClick = async () => {
  Object.assign(roleParams, {
    roleName: '',
    id: '',
  })
  dialogAddVisible.value = true
  console.log('addRoleClick')
}

/* click: 编辑职位按钮 */
const updateRoleName = async (row) => {
  Object.assign(roleParams, {
    roleName: row.roleName,
    id: row.id,
  })
  dialogAddVisible.value = true
}

/* click: 修改/新增职位抽屉的取消按钮 */
const handleCancelAddRole = () => {
  dialogAddVisible.value = false
}

/* click: 添加/修改抽屉的确定按钮 */
const handleConfirmAddRole = async () => {
  dialogAddVisible.value = false
  addOrUpdateRole()
  getHasRoles()
}
/* click: 删除按钮 */
const removeRole = async (row) => {
  let id = row.id
  let res = await reqDeleteRole(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasRoles()
  }
}

// click: 搜索按钮
const searchAbout = () => {
  getHasRoles()
  console.log('searchAbout')
}
/* click: 管理用户权限按钮, 点击获取选中权限及权限菜单 */
const setPower = async (row) => {
  Object.assign(roleParams, row)
  setRoleDraw.value = true
  let res = await reqGetRoleList(roleParams.id)
  if (res.code == 200) {
    roleList.value = res.data
    selectedArr.value = filterSelectArr(roleList.value, [])
    // console.log(selectedArr.value)
  } else {
    ElMessage({
      type: 'success',
      message: '失败',
    })
  }
}

/* func:筛选选中的权限 */
const filterSelectArr = (roleList, initArr) => {
  roleList.forEach((item) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}

/* click: 分配权限抽屉确认 */
const confirmClick = async () => {
  setRoleDraw.value = false
  let arr = treeRef.value.getCheckedNodes().map((item) => item.id)
  let arr1 = treeRef.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  console.log(arr1)

  let res = await reqAssignPermission(roleParams.id, permissionId)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
  } else {
    ElMessage({
      type: 'success',
      message: '分配权限失败',
    })
  }
}

/* click: 分配权限抽屉取消 */
const cancelClick = () => {
  setRoleDraw.value = false
}

onMounted(() => {
  getHasRoles()
})
</script>
<style scoped>
.form {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.form_edtxt {
  width: 70%;
  margin: 20px auto;
}

.below_content {
  margin-top: 15px;
}
</style>
